/**
 * 文件描述如下：
 * 1. 框选画线截图
 * 2.
 * 3.
 * 4.
 */

import { mainStore } from '@store'

let startX, startY, endX, endY, store
/**
 * 禁止场景旋转
 * @param 无传参
 * @returns 无返回值
 */

export const captureSelectedArea = () => {
  store = mainStore()

  // 开始框选 由于触发机制 需要线判断为false的情况
  if (!store.captureData.show) {
    window.ThreePerceivedEffect.controls.enableRotate = false
    window.ThreePerceivedEffect.renderer.domElement.addEventListener('mousedown', handleDown)
  }

  if (store.captureData.show) handleUm()
}

const handleDown = (e) => {
  startX = e.offsetX
  startY = e.offsetY
  store.captureData = {
    show: true,
    top: e.offsetY,
    left: e.offsetX,
    width: 2,
    height: 2,
  }
  store.captureData.showBtn = false

  document.addEventListener('mousemove', handleMove)
  document.addEventListener('mouseup', handleUp)
}

const handleMove = (e) => {
  endX = e.offsetX
  endY = e.offsetY
  store.captureData.width = endX - startX
  store.captureData.height = endY - startY
}

const handleUp = (e) => {
  document.removeEventListener('mousemove', handleMove)
  document.removeEventListener('mouseup', handleUp)

  store.captureData.showBtn = true
}

export const handleUm = () => {
  if (!store) return // 多种调用情况
  window.ThreePerceivedEffect.controls.enableRotate = true
  window.ThreePerceivedEffect.renderer.domElement.removeEventListener('mousedown', handleDown)
  store.captureData.show = false
  store.captureData.showBtn = false
}

// 点击保存后 生成截图
export const createImage = () => {
  // 从 three.js
  const canvas = window.ThreePerceivedEffect.renderer.domElement

  window.ThreePerceivedEffect.renderer.render(window.ThreePerceivedEffect.scene, window.ThreePerceivedEffect.camera)

  // 获取全部canvas的截图
  const base64Data = canvas.toDataURL('image/png')
  // 根据用户框选的进行切割裁剪
  const { left, top, width, height } = store.captureData

  cropImage(base64Data, left, top, width, height)
}

/**
 * 裁剪图片
 * @param {string} base64Data数据
 * @param {number} cropX 裁剪的x坐标
 * @param {number} cropY 裁剪的y坐标
 * @param {number} cropWidth 裁剪的宽度
 * @param {number} cropHeight 裁剪的高度
 * @returns
 */
const cropImage = (base64Data, cropX, cropY, cropWidth, cropHeight) => {
  let img = new Image()
  img.src = base64Data

  img.onload = () => {
    const canvas = document.createElement('canvas')
    canvas.width = cropWidth
    canvas.height = cropHeight
    const ctx = canvas.getContext('2d')
    ctx.drawImage(img, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight)
    const croppedDataUrl = canvas.toDataURL('image/png')
    img = null // 释放内存

    // 处理裁剪后的图像
    downloadImage(croppedDataUrl)
  }
}

/**
 * 下载图片
 * @param {string} dataUrl 图片数据
 * @returns 无返回值
 */
const downloadImage = (dataUrl) => {
  // 展示到页面上

  fetch(dataUrl)
    .then((res) => res.blob()) // 将 Base64 转换为 Blob
    .then((blob) => {
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      const name = '感知效果_' + Date.now()
      link.download = name
      document.body.appendChild(link)
      link.click()
      store.showPerceivedEffectImageData = {
        data: dataUrl,
        name: name,
        show: true,
      }

      // 释放内存
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    })
    .catch((err) => {
      console.error('Error downloading image:', err)
    })
}
